const fs = require('fs');
const path = require('path');

// API目录路径
const apiDir = path.join(__dirname, '..', 'preload', 'Api');
// 类型定义目录路径
const typesDir = path.join(__dirname, '..', 'renderer', 'src', 'types');

// 确保类型定义目录存在
if (!fs.existsSync(typesDir)) {
  fs.mkdirSync(typesDir, { recursive: true });
}

console.log('Generating API type definitions...');

// 为每个API文件生成类型定义
function generateApiTypes() {
  // 获取所有API文件
  const apiFiles = fs.readdirSync(apiDir).filter(file => file.endsWith('.ts') && file !== 'index.ts');

  apiFiles.forEach(file => {
    const apiName = path.basename(file, '.ts');
    const typeName = apiName.charAt(0).toUpperCase() + apiName.slice(1);
    
    // 读取API文件内容
    const content = fs.readFileSync(path.join(apiDir, file), 'utf-8');
    
    // 构建类型定义
    let typeDefinition = `// Auto-generated type definition for ${apiName}\n`;
    
    if (apiName === 'ipcApi') {
      typeDefinition += `export interface IpcApi {
  send: (channel: string, ...args: any[]) => void;
  invoke: (channel: string, ...args: any[]) => Promise<any>;
  on: (channel: string, listener: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => void;
  off: (channel: string, listener: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => void;
}\n`;
    } else {
      typeDefinition += `export interface ${typeName} {\n`;
      
      // 提取导出的函数
      const functionLines = content.split('\n').filter(line => line.includes(':') && line.includes('=>'));
      
      functionLines.forEach(line => {
        // 提取函数名和函数签名
        const functionNameMatch = line.match(/(\w+):\s*(\(.*\))\s*=>\s*(.*)/);
        if (functionNameMatch) {
          const [, functionName, params, returnType] = functionNameMatch;
          
          // 处理返回类型 - 将ipcRenderer.invoke(...)包装为Promise类型
          let processedReturnType;
          if (returnType.includes('ipcRenderer.invoke')) {
            processedReturnType = 'Promise<any>';
          } else if (returnType.includes('ipcRenderer.send')) {
            processedReturnType = 'void';
          } else {
            processedReturnType = returnType;
          }
          
          typeDefinition += `  ${functionName}: ${params} => ${processedReturnType};\n`;
        }
      });
      
      typeDefinition += '}\n';
    }
    
    // 写入类型定义文件
    const typeFilePath = path.join(typesDir, `${apiName}.d.ts`);
    fs.writeFileSync(typeFilePath, typeDefinition);
    console.log(`Generated ${typeFilePath}`);
  });
}

// 更新global.d.ts文件
function updateGlobalTypes() {
  const globalTypesPath = path.join(typesDir, 'global.d.ts');
  
  // 获取所有API文件
  const apiFiles = fs.readdirSync(apiDir).filter(file => file.endsWith('.ts') && file !== 'index.ts');
  
  // 构建新的导入语句和window接口定义
  const imports = apiFiles.map(file => {
    const apiName = path.basename(file, '.ts');
    const typeName = apiName.charAt(0).toUpperCase() + apiName.slice(1);
    
    if (apiName === 'ipcApi') {
      return `import type { IpcApi } from './${apiName}.d.ts';`;
    } else {
      return `import type { ${typeName} } from './${apiName}.d.ts';`;
    }
  }).join('\n');
  
  const windowProperties = apiFiles.map(file => {
    const apiName = path.basename(file, '.ts');
    
    if (apiName === 'ipcApi') {
      return `    ${apiName}: IpcApi;`;
    } else {
      const typeName = apiName.charAt(0).toUpperCase() + apiName.slice(1);
      return `    ${apiName}: ${typeName};`;
    }
  }).join('\n');
  
  // 生成新的global.d.ts内容
  const globalContent = `// Auto-generated global types
import { ElectronAPI } from '@electron-toolkit/preload';

// Auto-generated imports
${imports}

declare global {
  interface Window {
${windowProperties}
    electronApi: ElectronAPI;
  }
}

export {}; // Ensure this file is treated as a module
`;
  
  // 写入global.d.ts文件
  fs.writeFileSync(globalTypesPath, globalContent);
  console.log(`Generated ${globalTypesPath}`);
}

// 执行生成任务
generateApiTypes();
updateGlobalTypes();

console.log('Type generation completed!');